import pagesJson from '@/pages.json';
const key = '5332220b53f28948b876998a0e87da88'
export const loginPage = '/' + pagesJson.uniIdRouter.loginPage ?? '/uni_modules/uni-id-pages/pages/login/login-withpwd';

const getIp = () => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://restapi.amap.com/v3/ip?key=${key}`,
			success: ({
				data
			}) => {
				// province 、city 值有可能为[]
				let province = data.province.toString() ?? "over range",
					city = data.city.toString() ?? "over range"

				uni.setStorageSync('local', {
					province,
					city,
					time: Date.now()
				})

				resolve({
					province,
					city
				})
			},
			fail: (err) => {
				reject(new Error({
					message: JSON.stringify(err)
				}))
			}
		})
	})
}

const blogObj = uniCloud.importObject("blogObj",{ customUI: true })

export const loopReplaceEditorHtml = (html, replaceObj) => {
	let result = html
	for (let i = 0, len = replaceObj.length; i < len; i++) {
		result = result.replaceAll(replaceObj[i].filePath, replaceObj[i].fileID)
	}

	return result
}

export const StorageObject = {
	Local: "local",
	Articleid: "articleId"
}

export const dabaseObj = {
	Blog: "blog",
	Users: "uni-id-users"
}

export const getLocal = () => {
	return new Promise(async (resolve, reject) => {
		let historyLocal = uni.getStorageSync(StorageObject.Local)
		if (historyLocal && Date.now() - historyLocal.time < 60 * 60 * 1000) {
			return resolve(historyLocal)
		}
		const res = await getIp()
		if (res instanceof Error) {
			return reject(res)
		}
		return resolve(res)
	})

}

export const getStorage = (key) => {
	return uni.getStorageSync(key)
}

export const setStorage = (key, value) => {
	uni.setStorageSync(key, value)
}

export const removeStorage = (key) => {
	uni.removeStorageSync(key)
}

/** token 过期或 token 验证错误处理函数
 * 
 * @param {object} error 服务端的错误对象或自定义的错误对象
 * @returns {Boolean} 
 */
export const tokenExpiredOrErrorHandler = (error={}) => {
	if(!error.errCode || !error.code) return false
	let code = error.errCode ?? error.code
	if(code == "TOKEN_INVALID_TOKEN_EXPIRED" || code == "TOKEN_INVALID"){
		removeStorage("uni_id_token_expired")
		removeStorage("uni_id_token")
		removeStorage("uni-id-pages-userInfo")
		return true
	}
	return false
}

export const errhandler = (msg,method='navigateBack',delta=1,duration=1000) => {
	uni.showToast({
		title: msg,
		icon: "none",
		duration
	});
	setTimeout(() => {
		uni[method]({
			delta
		});
	}, duration);
}

/** 点赞处理逻辑，无感刷新
 * 
 * @param {Boolean} executeState 点赞执行状态（响应式）
 * @param {String} userId 当前用户 Id
 * @param {String} articleId 点赞文章 Id
 * @param {Object} articleObj 文章对象（响应式）
 * @param {Boolean} callback 回调函数 执行成功的回调
 * @returns {Object} 执行成功或失败
 */
export const likeClick = async (userId,articleId,articleObj,updateAvatarGroup,callback) => {
	
	if(!articleId){
		return {
			status: false,
			reason: "缺少articleId"
		}
	}
	// 采用无感操作

	let requestStatus = true;  // 标识请求接口状态，默认请求成功
	if (!articleObj.hasLike) {
		articleObj.like_count += 1;
	} else {
		articleObj.like_count -= 1;
	}
	// articleObj.hasLike 更新是异步的
	const changFlag = !articleObj.hasLike;
	articleObj.hasLike = !articleObj.hasLike;
	// 调用点赞接口
	try {
		if (changFlag) {
			
			updateAvatarGroup && typeof updateAvatarGroup == 'function' && updateAvatarGroup("add")
			const res = await blogObj.addLikeCount(articleId, userId);
			
			articleObj.blogLikeId = res.newRecordId;
			// 通知主页更新状态
			callback && typeof callback == "function" && fn()
		} else {
			updateAvatarGroup && typeof updateAvatarGroup == 'function' && updateAvatarGroup("remove")
			if(!articleObj.blogLikeId) {
				articleObj.blogLikeId = await blogObj.blogLikeIdQuety(articleId)
			}
			await blogObj.addLikeCount(articleId, userId, articleObj.blogLikeId, false);
		}
	} catch (e) {
		console.log(e);
		requestStatus = false;
		uni.showToast({
			title: e.message,
			icon: 'error'
		});
	} finally {
		// 成功
		if (requestStatus) return {status: true, msg: "更新成功"};
		// 失败
		if (changFlag) {
			articleObj.like_count -= 1;
			updateAvatarGroup && typeof updateAvatarGroup == 'function' && updateAvatarGroup("remove")
		} else {
			articleObj.like_count += 1;
			updateAvatarGroup && typeof updateAvatarGroup == 'function' && updateAvatarGroup("add")
		}
		articleObj.hasLike = !articleObj.hasLike;
		return {
			status: false,
			reason: "更新失败"
		}
	}
}

/**
 * @param {Object} data 			comment数据
 * @param {String} orderByField		排序字段 date | likeCount
 * @param {String} order			排序方式 desc | asc
 * @returns {Array}
 */
export const sortCommentData = (data,orderByField="date",order="desc") => {
	let parentList = [],childList = [], parentMap = new Map()
	if(!data.length) return []
	orderByField = orderByField.toLowerCase()
	order = order.toLowerCase()
	if(orderByField != "date" && orderByField != "likeCount") return []
	if(order != "desc" && order != "asc") return []
	
	orderByField = orderByField == "date" ? "comment_date" : "like_count"
	
	if(order == "desc"){
		data =  data.sort((pre,next) =>{
			return next[orderByField] - pre[orderByField]
		})
	}else{
		data =  data.sort((pre,next) =>{
			return pre[orderByField] - next[orderByField]
		})
	}
		
	for(let i = 0,len = data.length; i<len; i++){
		!data[i].comment_type && parentList.push(data[i]) && parentMap.set(data[i]._id, parentList.length-1)
		data[i].comment_type && childList.push(data[i]) 
	}
	
	for(let i = 0,len = childList.length;i<len;i++){
		const index = parentMap.get(childList[i].reply_comment_id)
		if(!parentList[index].children){
			parentList[index].children = []
		}
		parentList[index].children.push(childList[i])	
	}

	return parentList
}


export const getUserAvatar = (data) => {
	const url = data.user_id?.length && data.user_id[0].avatar_file&&data.user_id[0].avatar_file.url ? data.user_id[0].avatar_file.url : '/static/images/user-default.jpg'
	// console.log(url);
	return url
}

export const getInfo = (data) => {
	return data.user_id && data.user_id.length && data.user_id[0] ? data.user_id[0] : {}
}
